<template>
	<div class="left-box">
		<!--	选择单位		-->
		<div class="heade-wrapper">
			<a-input-group compact  style="display: flex;">
				<!--	选择多维组织单位		-->
				<a-select
					class="heade-left-box"
					v-model="businessAccountId"
					:disabled="unallowedChangeBusinessAccount"
				>
					<a-select-option v-for="it in businessAccountList" :value="it.id" :key="it.id">
						{{ it.name }}
					</a-select-option>
				</a-select>

				<a-input-search
					class="heade-right-box"
					:placeholder="placeText"
					v-model.trim="searchValue"
					@search="onSearch"
				>
				</a-input-search>
			</a-input-group>
		</div>

		<div class="content-wrapper">
			<top-bottom-layout :isShowDown="isShowDown">
				<template #top>
					<transfer-tree
						:checkable="checkable"
						:defaultChecked="defaultChecked"
						:checkedList="checkedList"
						:defaultSelected="defaultSelected"
						:defaultExpandedKeys="defaultExpandedKeys"
						:treeData="treeData"
						@toCheckedNode="onChecked"
						@toSelectNode="onSelected"
					></transfer-tree>
				</template>
				<template #middle>
					<a-radio-group
						v-model="radioValue"
						@change="onRadioChange"
					>
						<template v-for="(item, index) in radioList">
							<a-radio
								v-if="item.value === 'member' && selectType.includes('Member')"
								:key="index"
								:value="item.value"
							>
								{{ item.label }}
							</a-radio>
							<a-radio
								v-if="item.value === 'role' && showRole"
								:key="index"
								:value="item.value"
							>
								{{ item.label }}
							</a-radio>
						</template>
					</a-radio-group>
				</template>
				<template #bottom>
					<scroll-list
						v-if="radioValue === 'member' && isMemberSearch === false"
						panel="BusinessDepartment"
						command="memberList"
						ref="scrollList"
						key="member"
						:firstLoadSearch="false"
						:showOtherProp="true"
						:otherProps="memberOtherProps"
					>
					</scroll-list>
					<scroll-list
						v-else-if="radioValue === 'member' && isMemberSearch === true"
						panel="BusinessDepartment"
						command="search"
						ref="scrollList"
						key="member"
						:firstLoadSearch="false"
						:showOtherProp="true"
						:otherProps="memberOtherProps"
					>
					</scroll-list>
					<scroll-list
						v-else-if="radioValue === 'role'"
						panel="BusinessDepartment"
						command="businessRoleList"
						ref="scrollList"
						key="role"
						:firstLoadSearch="false"
						:showOtherProp="true"
						:otherProps="memberOtherProps"
					>
					</scroll-list>
				</template>
			</top-bottom-layout>
		</div>
	</div>
</template>

<script>
import transferTree from '@/components/transferTree.vue';
import scrollList from '@/components/scrollList';
import topBottomLayout from '@/components/topBottomLayout.vue';
import { getPanelData } from '@/api/modules/SelectOrgApi';
import { mapActions, mapState } from 'vuex';
import { ACTION_ADD_ENTITY, ACTION_REMOVE_ENTITY, ACTION_TOGGLE_ENTITY } from '@/store/actionTypes';
import { EntityTypes } from '@/utils/orgConstants';
import { BtnType, Dialog } from '@/components/dialog';
import { CheckUtils } from '@/utils/checkUtils';
import { TreeUtils } from '@/utils/treeUtils';
import { MaskAsync } from '@/utils/Mask.js';
import { getTreeItems} from '@/utils/utils';


export default {
	name: 'BusinessDepartment',
	components: {
		transferTree,
		scrollList,
		topBottomLayout
	},
	inject: ['app'],
	data() {
		return {
			currentAccountId: '',
			businessAccountId: '',

			businessDepartment: {},
			businessAccountList: [],
			isMemberSearch: false,
			searchValue: '',
			defaultChecked: [],
			treeData: [],
			checkedList: [],
			defaultExpandedKeys: [],
			defaultSelected: [],
			radioList: [
				{ label: this.$i18n('org.member.label'), value: 'member' },
				{ label: this.$i18n('org.role.label'), value: 'role' }
			],
			radioValue: 'member',
			activeNodeType: 'BusinessAccount',
			metadataList: [],
			deptList: [],
			// memberOtherProps: ['postName'],

			isShowDown: false
		};
	},
	created() {
		if (!this.orgSelect.selectType.includes(EntityTypes.Member)) {
			this.isShowDown = true;
		}
	},
	activated() {
		const { id: accountId } = this.app().switchAfterUnit;
		if (this.$isChangeAccount(this, accountId)) {
			this.onChangeAccount({
				id:accountId
			});
		}
	},
	computed: {
		...mapState('selectData', ['selectedEntityMap', 'selectedList']),
		showCheckboxInDeptTree() {
			return this.orgSelect.showCheckboxInDeptTree;
		},
		orgSelect() {
			return this.app().orgSelect;
		},
		selectType() {
			return this.orgSelect.selectType || [];
		},
		businessDepartmentId() {
			return this.businessDepartment.id || '';
		},
		unallowedChangeBusinessAccount() {
			return this.orgSelect.unallowedChangeBusinessAccount;
		},
		checkable() {
			return this.orgSelect.selectType.includes(EntityTypes.BusinessDepartment);
		},
		placeText() {
			let radio = this.radioValue;
			let { selectMember, selectBusinessDept } = this.onCanSelectType();
			let res = this.$i18n('selectPeople.input',`${this.$i18n('selectPeople.bussinessOraganization.department.label')}/${this.$i18n('org.member.label')}`);
			if (!selectMember && selectBusinessDept) {
				res = this.$i18n('selectPeople.input',`${this.$i18n('org.department.label')}`);
			} else if (selectMember && !selectBusinessDept) {
				res = this.$i18n('selectPeople.input',this.$i18n('org.member.label'));
			} else if (radio === 'member') {
				res = this.$i18n('selectPeople.input',`${this.$i18n('org.department.label')}/${this.$i18n('org.member.label')}`);
			} else if (radio === 'role') {
				res = this.$i18n('selectPeople.input',this.$i18n('org.role.label'));
			} else {
				res = this.$i18n('selectPeople.bussinessOraganization.department.label');
			}
			return res;
		},
		showRole() {
			return !this.orgSelect.hiddenRoleOfDepartment
				&& this.selectType.includes('BusinessRole')
				&& this.activeNodeType === 'BusinessDepartment';
		},
		memberOtherProps() {
			return this.onSetOtherProps(['postName'])
		},
    isShowCheckboxTree() {
      return this.app().isShowCheckboxTree;
    }
	},
	watch: {
		businessAccountId(val) {
			this.treeData = [];
			this.businessDepartment = {};
			if (this.$refs.scrollList) {
				this.$refs.scrollList.initProps();
			}
			if (!val) {
				return;
			}
			this.getTreeData();
		},
		selectedEntityMap: {
			deep: true,
			handler(selectedEntities) {
				this.dealSelected(selectedEntities);
			}
		}
	},
	methods: {
		...mapActions('selectData', [ACTION_TOGGLE_ENTITY, ACTION_ADD_ENTITY, ACTION_REMOVE_ENTITY]),
		/**
		 *切换单位
		 * @param data
		 */
		onChangeAccount(data) {
			if (!this.$isChangeAccount(this, data.id)) {
				return;
			}
			this.currentAccountId = data.id;
			this.radioValue = 'member';
			this.getBusinessAccountList();
		},
		/**
		 * 获取多维组织列表
		 */
		getBusinessAccountList() {
			const _t = this;
			this.businessAccountList = [];
			this.businessAccountId = '';
			if (!this.currentAccountId) {
				return;
			}
			// 标记单位
			this.$changeAccount(this, this.currentAccountId);
			var alwaysShowBusiness = this.app().orgSelect;
			getPanelData({
				panel: 'BusinessDepartment',
				command: 'businessAccountList',
				arguments: { accountId: this.currentAccountId, alwaysShowBusiness:alwaysShowBusiness}
			}).then((res) => {
				const currentBusinessAccount = _t.orgSelect.currentBusinessAccount;
				this.businessAccountList = res.data;
				if (currentBusinessAccount) {
					this.businessAccountId = currentBusinessAccount;
				} else if (this.businessAccountList[0]) {
					this.businessAccountId = this.businessAccountList[0].id;
				}
			});
		},
		/**
		 * 获取部门树
		 * @returns {Promise<void>}
		 */
		async getTreeData() {
			let params = {
				panel: 'BusinessDepartment',
				command: 'businessDepartmentList',
				arguments: {
					accountId: this.currentAccountId,
					businessAccountId: this.businessAccountId
				}
			};
			let res = await getPanelData(params);
			if (Number(res.code) === 0 && res.data) {
				this.businessDepartment = res.data;
				this.treeData = [res.data];
				if (this.treeData.length > 0) {
					this.$set(this.defaultExpandedKeys, 0, this.treeData[0].id);
					this.$set(this.defaultSelected, 0, this.treeData[0].id);
					this.onHandlerTreeDisabled(this.treeData);
					this.dealSelected(this.selectedEntityMap);
				}
			}
		},
		/**
		 * 处理已经选择的数据
		 * @param selectedEntityMap
		 */
		dealSelected(selectedEntityMap) {
			if (!selectedEntityMap) {
				return;
			}
			let selectedKeys = [];
			let pathKeys = Object.keys(selectedEntityMap);
			if (pathKeys.length) {
				for (let item of pathKeys) {
					if (item.indexOf(EntityTypes.BusinessAccount) === 0
						|| item.indexOf(EntityTypes.BusinessDepartment) === 0) {
						selectedKeys.push(item.split('|')[1]);
					}
				}
			}
			this.checkedList = selectedKeys;
		},

		/**
		 * 节点被选中
		 * @param nodeData 当前节点的数据
		 * @param nodeEl 被选择的元素
		 * @returns {Promise<void>}
		 */
		@MaskAsync
		async onChecked(nodeData, nodeEl) {
			let { showCheckboxInDeptTree, isConfirmExcludeSubDepartment } = this.orgSelect;
			// 当前节点是否被选中
			let currentNodeState = nodeEl.checked;
			console.log('onChecked -> nodeData', nodeData, currentNodeState);
			let currentNode = nodeData.checkeds[0];
			let nodeType = currentNode.type;


			let notIncludeSubDept = [];
			let checkContext = {
				currentPanel: 'BusinessDepartment',
				notIncludeSubDept
			};
      let treeItems = this.isShowCheckboxTree ? getTreeItems(currentNode) : [currentNode];
			// 取消选择
			if (currentNodeState) {
				this[ACTION_REMOVE_ENTITY]({
					entities:  [currentNode]
				});
				return;
			}
      if(this.isShowCheckboxTree) {
        // 提示是否排查子部门
        let btnType = BtnType.OK;
        if (currentNode.children && currentNode.children.length && nodeType === 'BusinessDepartment') {
          btnType = await Dialog.confirm({
            msg: `"${currentNode.name}${this.$i18n('selectPeople.ConfirmChildDept')}"`,
            okText: this.$i18n('common.include.label'),
            cancelText: this.$i18n('common.not.include.label')
          });
        }
        if (btnType === BtnType.CLOSE) {
          return;
        }
        if (btnType === BtnType.CANCEL) {
          // notIncludeSubDept.push(currentNode.id);
          treeItems = [currentNode] //不包含只处理当前节点
        }
        let result = await CheckUtils.doCheckEntity(currentNode, checkContext);
        if (!result) {
          return;
        }
        this[ACTION_ADD_ENTITY]({
          entities: treeItems,
          notIncludeSubDept
        });
      } else {
        if (showCheckboxInDeptTree ) {
				// 选择单位时勾选子部门
				if (nodeType === EntityTypes.BusinessAccount && !this.selectType.includes(EntityTypes.BusinessAccount)) {
					let data = TreeUtils.findDeptChildren(nodeData.checkeds[0].children, this.selectedEntityMap,false);
					let entities = [];
					for (let entity of data) {
						let result = await CheckUtils.doCheckEntity(entity, checkContext);
						if (!result) {
							continue;
						}
						entities.push(entity);
					}
					if (entities.length) {
						this[ACTION_ADD_ENTITY]({ entities: entities });
					}
					return;
				}

				// 老版本数据组件，只是选中效果
				let result = await CheckUtils.doCheckEntity(currentNode, checkContext);
				if (!result) {
					return;
				}
				// 老版本的树显示checkbox,选择什么就是什么
				this[ACTION_ADD_ENTITY]({
					entities: [currentNode]
				});
				return;
			}

			// 提示是否排查子部门
			let btnType = BtnType.OK;
			if (isConfirmExcludeSubDepartment && currentNode.children && currentNode.children.length && nodeType === 'BusinessDepartment') {
				btnType = await Dialog.confirm({
					msg: `"${currentNode.name}${this.$i18n('selectPeople.ConfirmChildDept')}"`,
					okText: this.$i18n('common.include.label'),
					cancelText: this.$i18n('common.not.include.label')
				});
			}
			if (btnType === BtnType.CLOSE) {
				return;
			}
			if (btnType === BtnType.CANCEL) {
				notIncludeSubDept.push(currentNode.id);
        treeItems = [currentNode] //不包含只处理当前节点
			}
			let result = await CheckUtils.doCheckEntity(currentNode, checkContext);
			if (!result) {
				return;
			}
      
      this[ACTION_TOGGLE_ENTITY]({
          entities: treeItems,
          notIncludeSubDept
        });
      }
		},
		onRadioChange(e) {
			let radio = e.target.value;
			this.searchValue = '';
			if (radio === 'member') {
				this.$nextTick(() => {
					this.onSearchData();
				});
			} else if (radio === 'role') {
				this.$nextTick(() => {
					this.onSearchData();
				});
			}
		},
		onSearch(val) {
			if (this.isShowDown) {
				this.isShowDown = false;
			}
			this.onSearchData();
		},
		onSearchData() {
			if (!this.businessAccountId || !this.businessDepartmentId) {
				return;
			}
			if (this.treeData.length === 0) {
				return
			}

			let searchType = this.onBackSelectType();

			let { accessFileSecretLevel } = this.orgSelect;
			let data = {
				keyword: this.searchValue,
				accountId: this.currentAccountId,
				businessAccountId: this.businessAccountId,
				businessDepartmentId: this.businessDepartmentId,
				searchType: searchType,
				accessFileSecretLevel
			};

			this.isMemberSearch = false;
			if (this.radioValue === 'member' && this.searchValue !== '') {
				this.isMemberSearch = true;
				data = {
					keyword: this.searchValue,
					unitId: this.businessAccountId,
					searchType: searchType,
					accessFileSecretLevel
				};
			}
			this.onLoadScrollList(data)
		},
		onCanSelectType() {
			let selectBusinessDept = this.orgSelect.selectType.includes(EntityTypes.BusinessDepartment);
			let selectMember = this.orgSelect.selectType.includes(EntityTypes.Member);
			return { selectBusinessDept, selectMember };
		},
		onSelected(data) {
			let nodeData = data.selected
			let { selectMember, selectBusinessDept } = this.onCanSelectType();
			if (!selectMember) {
				return;
			}
			this.isMemberSearch = false
			if (nodeData.length) {
				this.activeNodeType = nodeData[0].type;
				this.businessDepartment = nodeData[0];
				if (this.activeNodeType === 'BusinessAccount') {
					this.radioValue = 'member';
				}
				let { accessFileSecretLevel } = this.orgSelect;
				let searchType = this.onBackSelectType()
				let data = {
					accountId: this.currentAccountId,
					businessAccountId: this.businessAccountId,
					businessDepartmentId: this.businessDepartmentId,
					searchType: searchType,
					accessFileSecretLevel
				};
				this.onLoadScrollList(data)

			}
		},
		onBackSelectType() {
			let { selectMember, selectBusinessDept } = this.onCanSelectType();
			let searchType = '';
			if (selectBusinessDept && selectMember) {
				searchType = 'BusinessDepartment,Member';
			} else if (selectBusinessDept) {
				searchType = 'BusinessDepartment';
			} else {
				searchType = 'Member';
			}
			return searchType
		},
		onLoadScrollList(data) {
			this.$nextTick(() => {
				this.$refs.scrollList.search(data);
			});
		},
		/**
		 * 人员【密级】展示处理
		 * @param {Array} list 默认展示的人员信息
		*/
		onSetOtherProps(list) {
			if (this.orgSelect.showSecretLevel) {
				list.unshift('secretLevel')
			}
			return list
		},
		/**
		 * 多维组织单位 disabled 处理
		 * @param {Array} treeData
		*/
		onHandlerTreeDisabled(treeData) {
			const { includeElements, showCheckboxInDeptTree, selectType } = this.orgSelect;
			if (includeElements == '' && !showCheckboxInDeptTree && treeData[0].type === EntityTypes.BusinessAccount && !selectType.includes(EntityTypes.BusinessAccount)) {
				treeData[0].disabled = true;
			}
		}
	}
};
</script>
